package org.p2psimulator.engine;

import java.util.concurrent.Callable;
import org.p2psimulator.config.ThreadConfig;
import org.p2psimulator.entity.Network;

public abstract class AbstractTask<T> implements Runnable, Callable<T> {

	protected Boolean locked = false;
	protected Boolean alive = false;

	public boolean isLocked() {
		return locked;
	}

	public void setLocked(boolean locked) {
		this.locked = locked;

	}

	static int cnt= 0;
	public synchronized void synchronizeTasks() {
		locked = true;
		if (locked) {
			try {
				cnt++;
//				System.err.println(" WAIT + " + cnt);
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public synchronized void wakeup() {

		cnt--;
//		System.err.println(" WAIT - " + cnt);
		locked = false;
		notify();
	}

	public void waitOnNetwork() {

		while (Network.isRunning()) {

			// System.err.println(">>>>>>>>>>>>>>>>>>>>> Esperando a rede");
			try {
				Thread.sleep(ThreadConfig.SYNCH_TIME_MS);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public void setLocked(Boolean locked) {
		this.locked = locked;
	}

	public Boolean isAlive() {
		return alive;
	}

	public void setAlive(Boolean alive) {
		this.alive = alive;
	}
}
